package com.ops.service;

import com.ops.entity.Fault;
import com.ops.entity.Inspection;
import com.ops.entity.OpsTask;
import com.ops.repository.FaultRepository;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class FaultService {

    @Autowired
    private FaultRepository faultRepository;

    /**
     * 导入Excel文件中的故障数据
     * 
     * @param file 上传的Excel文件
     * @param reportUuid 报告UUID
     * @param hospitalId 医院ID
     * @param demandYear 需求年份
     * @return 成功导入的记录数
     * @throws Exception 导入过程中可能出现的异常
     */
    @Transactional
    public int importExcel(MultipartFile file, String reportUuid, String hospitalId, String demandYear) throws Exception {
        // 先删除已存在的数据，使用 deleteAll 确保事务同步
        List<Fault> existingFaults = faultRepository.findByReportUuid(reportUuid);
        if (!existingFaults.isEmpty()) {
            faultRepository.deleteAll(existingFaults);
            faultRepository.flush(); // 强制刷新，确保删除操作立即生效
        }

        List<Fault> faultsToSave = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过表头

                Fault fault = new Fault();
                String queueId = getCellValueAsString(row.getCell(0));
                demandYear = getCellValueAsString(row.getCell(1));
                hospitalId = getCellValueAsString(row.getCell(3));

                // 设置基本信息
                fault.setQueueId(queueId);
                fault.setReportUuid(reportUuid);
                fault.setDemandYear(demandYear);
                fault.setHospitalId(hospitalId);    // 医院ID

                // 从Excel读取数据
                fault.setHospitalName(getCellValueAsString(row.getCell(2)));  // 医院名称

                // 故障时间
                String faultDate = getCellValueAsString(row.getCell(4));
                if (faultDate != null && !faultDate.isEmpty()) {
                    fault.setFaultDate(parseDateTime(faultDate));
                }
                fault.setFaultTimeSlot(getCellValueAsString(row.getCell(5)));
                fault.setCauseType(getCellValueAsString(row.getCell(6)));     // 原因类型
                fault.setCauseDesc(getCellValueAsString(row.getCell(7)));     // 原因描述
                fault.setSolution(getCellValueAsString(row.getCell(8)));      // 解决办法
                fault.setIsResolved(getCellValueAsString(row.getCell(9)));    // 是否解决
                fault.setHandler(getCellValueAsString(row.getCell(10)));       // 处理人
                // 根据唯一索引查找现有记录
//                Optional<Fault> existingFault = faultRepository.findByReportUuidAndQueueIdAndHospitalIdAndDemandYear(
//                        reportUuid, queueId, hospitalId, demandYear
//                );
//                // 如果存在记录，则更新ID
//                existingFault.ifPresent(value -> fault.setId(value.getId()));

                faultsToSave.add(fault);
            }
        }

        // 批量保存新数据
        if (!faultsToSave.isEmpty()) {
            faultRepository.saveAll(faultsToSave);
            faultRepository.flush(); // 确保保存操作立即生效
        }

        return faultsToSave.size();
    }

    /**
     * 解析日期时间字符串为LocalDateTime对象
     * 
     * @param dateStr 日期时间字符串
     * @return 解析后的LocalDateTime对象，解析失败时返回null
     */
    private LocalDateTime parseDateTime(String dateStr) {
        try {
            if (dateStr.contains(".")) {
                dateStr = dateStr.substring(0, dateStr.indexOf("."));
            }

            DateTimeFormatter formatter;
            if (dateStr.length() > 16) {
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            } else {
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            }
            return LocalDateTime.parse(dateStr, formatter);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取单元格的字符串值
     * 
     * @param cell Excel单元格对象
     * @return 单元格的字符串值，对于数值类型保留整数，对于日期类型格式化为yyyy-MM-dd HH:mm:ss
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) return null;

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getLocalDateTimeCellValue()
                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }
                return String.format("%.0f", cell.getNumericCellValue());
            default:
                return null;
        }
    }

    public List<Fault> getFaults(String reportUuid, String hospitalId, String demandYear) {
        return faultRepository.findByReportUuidAndHospitalIdAndDemandYearOrderByFaultDateDesc(
            reportUuid, hospitalId, demandYear
        );
    }
    public Map<String, Object> getFaultStats(String reportUuid) {
        Map<String, Object> stats = new HashMap<>();

        // 查询所有故障
        List<Fault> faults = faultRepository.findByReportUuid(reportUuid);

        // 计算总故障数
        stats.put("totalFaults", faults.size());

        // 统计第三方故障
        long thirdPartyFaults = faults.stream()
                .filter(f -> "外部原因".equals(f.getCauseType()))
                .count();
        stats.put("thirdPartyFaults", (int) thirdPartyFaults);

        // 统计已解决的第三方故障
        long thirdPartyResolvedFaults = faults.stream()
                .filter(f -> "外部原因".equals(f.getCauseType()) && "是".equals(f.getIsResolved()))
                .count();
        stats.put("thirdPartyResolvedFaults", (int) thirdPartyResolvedFaults);

        // 统计内部故障
        long internalFaults = faults.stream()
                .filter(f -> "内部原因".equals(f.getCauseType()))
                .count();
        stats.put("internalFaults", (int) internalFaults);

        // 统计已解决的内部故障
        long internalResolvedFaults = faults.stream()
                .filter(f -> "内部原因".equals(f.getCauseType()) && "是".equals(f.getIsResolved()))
                .count();
        stats.put("internalResolvedFaults", (int) internalResolvedFaults);

        return stats;
    }

    public List<Map<String, Object>> getMonthlyFaultStats(String reportUuid, String hospitalId, String demandYear) {
        List<Fault> faults = faultRepository.findByReportUuidAndHospitalIdAndDemandYearOrderByFaultDateDesc(
            reportUuid, hospitalId, demandYear
        );

        // 初始化12个月的数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", i);
            monthData.put("totalFaults", 0);
            monthData.put("thirdPartyFaults", 0);
            monthData.put("internalFaults", 0);
            result.add(monthData);
        }

        // 统计每月的故障数据
        for (Fault fault : faults) {
            if (fault.getFaultDate() != null) {
                int month = fault.getFaultDate().getMonthValue();
                Map<String, Object> monthData = result.get(month - 1);
                
                // 更新总故障数
                monthData.put("totalFaults", (int)monthData.get("totalFaults") + 1);
                
                // 根据故障类型更新相应计数
                if ("外部原因".equals(fault.getCauseType())) {
                    monthData.put("thirdPartyFaults", (int)monthData.get("thirdPartyFaults") + 1);
                } else if ("内部原因".equals(fault.getCauseType())) {
                    monthData.put("internalFaults", (int)monthData.get("internalFaults") + 1);
                }
            }
        }

        return result;
    }
}